<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use addons\litestore\model\Litestoreorder;
use app\admin\model\OrderSfLog;
use app\common\library\Sms;

// 脚本时间
class Crontabs extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    // 自动接单
    // 根据距离分配订单
    public function freight()
    {
        if ($this->request->request('type') != 'freight') {
            return $this->view->fetch('index/index');
        }
        // $this->longitude = 120.275123;
        // $this->latitude = 30.208345;
        $distance_range = config('site.distance_range') * 1000;
        if ($distance_range) {
            // 距离
            // 查询已付款，未受理的订单
            $orders =  db('litestore_order a')->field('a.id,b.lng,b.lat,b.phone,b.name')->join('litestore_order_address b', 'a.id = b.order_id')->where(['a.pay_status' => '20', 'a.freight_status' => '10'])->select();


            if ($orders) {
                foreach ($orders as $order) {
                    $this->lng = $order['lng'];
                    $this->lat = $order['lat'];
                    $sf_log = OrderSfLog::where('order_id', $order['id'])->where('status', 20)->value('sf_id');

                    $filter = [];
                    if ($sf_log) {
                        $filter['a.user_id'] = ['<>', $sf_log];
                    }
                    $sf =  db('user_id_card a')->field("
                        a.user_id,
                        a.name,
                        a.mobile,
                        a.lng,
                        a.lat,
                        ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$this->lat}*PI()/180-lat*PI()/180)/2),2)+COS({$this->lat}*PI()/180)*COS(lat*PI()/180)
                        *POW(SIN(($this->lng*PI()/180-lng*PI()/180)/2),2)))*1000) as distance")
                        ->join('user b', 'b.id = a.user_id')->where('b.start_work', 1)
                        ->where($filter)->where('a.status', 1)->having('distance <= ' . $distance_range)->order('distance')->find();

                    if ($sf) {
                        // 受理该订单
                        if (Litestoreorder::where('id', $order['id'])->update(['sf_id' => $sf['user_id'], 'freight_status' => '20', 'freight_time' => time()])) {
                            // 增加师傅接单记录
                            $data['order_id'] = $order['id'];
                            $data['sf_id'] = $sf['user_id'];
                            $data['name'] = $sf['name'];
                            $data['mobile'] = $sf['mobile'];
                            if ((new OrderSfLog())->save($data)) {
                                // 其它逻辑条件。比如小程序或公共号，短信等通知已接单受理
                                $params = ['number' => $order['phone'], 'consignee' => $order['name']];
                                $sms = Sms::send_o($sf['mobile'], $params);
                                if (!$sms) {
                                    echo '短信发送失败';
                                }
                                echo '接单成功';
                                continue;
                            }
                        }
                        echo '受理该订单失败，请检查' . json_encode(['order_id' => $order['id'], 'sf_id' => $sf['user_id']]);
                        continue;
                    }
                    echo '暂无订单匹配师傅';
                }
            }else{
                echo '暂无订单';
            }
        }
    }
}
